# -*- coding: UTF-8 -*-
'''
@Project: stock
@File: Urllib.py
@Notes: 
@Author: zhuyoucheng
@Date: 2021/4/2 0002 10:25
'''

import urllib
from urllib import request, response, parse
import json

class Urllib(object):

    #GET方法
    def http_get(self, url):
        response = urllib.request.urlopen(url)  # 调用urllib2向服务器发送get请求
        res=response.read()  # 获取服务器返回的页面信息
        return res.decode(encoding="utf-8")

    #POST方法
    def http_post(self, url, data, headers={'Content-Type': 'application/json'}):
        #转码为bytes
        bytes_data = bytes(data, 'utf8')
        req = urllib.request.Request(url=url, headers=headers, data=bytes_data)  # 生成页面请求的完整数据
        response = urllib.request.urlopen(req)  # 发送页面请求
        res=response.read()  # 获取服务器返回的页面信息
        return res.decode(encoding="utf-8")


    #PUT方法
    def http_put(self, url, data, header={'Content-Type': 'application/json'}):
        # 转码为bytes
        bytes_data = bytes(data, 'utf8')
        request = urllib.request.Request(url, bytes_data)
        if header:
            for key in header:
                request.add_header(key, header[key])
        request.get_method = lambda: 'PUT'  # 设置HTTP的访问方式
        print(request)
        request = urllib.request.urlopen(request)
        res=request.read()
        return res.decode(encoding="utf-8")


    #DELETE方法
    def http_delete(self, url, data, header={'Content-Type': 'application/json'}):
        # 转码为bytes
        bytes_data = bytes(data, 'utf8')
        request = urllib.request(url, bytes_data)
        if header:
            for key in header:
                request.add_header(key, header[key])
        request.get_method = lambda: 'DELETE'  # 设置HTTP的访问方式
        request = urllib.urlopen(request)
        res=request.read()
        return res.decode(encoding="utf-8")


